import 'dart:async';
import 'dart:io';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:app_settings/app_settings.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

// 蓝牙权限混入类
mixin BluetoothPermissionMixin {
  /// 检查蓝牙权限状态，并执行相应的回调
  ///
  /// [onSuccess] - 权限授予成功后的回调
  /// [onFailed] - 权限授予失败或蓝牙关闭时的回调
  StreamSubscription<CustomBluetoothAdapterState>
      bluetoothPermissionBluetoothPermission(
          {VoidCallback? onSuccess, VoidCallback? onFailed}) {
    return BluetoothPermissionsManager.listenToBluetoothAdapterState((event) {
      debugPrint('蓝牙适配器状态: $event');
      switch (event) {
        case CustomBluetoothAdapterState.unknown:
          debugPrint('蓝牙适配器状态未知');
          // iOS系统蓝牙开启时，未开始app蓝牙权限请求
          break;
        case CustomBluetoothAdapterState.unavailable:
          debugPrint('蓝牙适配器不可用');
          break;
        case CustomBluetoothAdapterState.unauthorized:
          debugPrint('蓝牙适配器未授权');
          // iOS系统蓝牙开启时，但app蓝牙权限授权拒绝
          if (Platform.isIOS) {
            _vmShowPermissionDeniedDialog();
          }
          break;
        case CustomBluetoothAdapterState.turningOn:
          debugPrint('蓝牙适配器正在开启');
          break;
        case CustomBluetoothAdapterState.on:
          debugPrint('蓝牙适配器已开启');
          // iOS系统蓝牙开启时，且app蓝牙权限已经授权
          if (WidgetsBinding.instance.lifecycleState ==
              AppLifecycleState.resumed) {
            // App在前台运行
            if (Platform.isIOS) {
              if (onSuccess != null) {
                onSuccess();
              }
            } else if (Platform.isAndroid) {
              _vmRequestBluetoothPermission(() {
                // 请求蓝牙权限成功后，开始扫描
                Future.delayed(
                  const Duration(milliseconds: 300),
                  () {
                    if (onSuccess != null) {
                      onSuccess();
                    }
                  },
                );
              });
            }
          }
          break;
        case CustomBluetoothAdapterState.turningOff:
          debugPrint('蓝牙适配器正在关闭');
          break;
        case CustomBluetoothAdapterState.off:
          debugPrint('蓝牙适配器已关闭');
          // 停止扫描
          if (onFailed != null) {
            onFailed();
          }
          if (Platform.isAndroid) {
            // 蓝牙未开启，提示用户开启蓝牙
            _vmShowEnableBluetoothDialog();
          }
          break;
      }
    });
  }

  // 请求蓝牙权限
  _vmRequestBluetoothPermission(VoidCallback? successed) async {
    BluetoothPermissionsManager.checkAllPermissions().then((isGranted) {
      if (isGranted) {
        debugPrint('蓝牙权限已授予');
        if (successed != null) {
          successed();
        }
      } else {
        debugPrint('蓝牙权限未授予');
        // 请求蓝牙权限
        SystemPermissionUtil.requestBluetoothPermission(
          onSuccess: () {
            debugPrint('蓝牙权限申请成功');
            if (successed != null) {
              successed();
            }
          },
          onCancel: () {
            debugPrint('取消');
          },
          onFailed: (permission) {
            debugPrint('蓝牙权限申请失败: $permission');
            _vmShowPermissionDeniedDialog();
          },
        );
      }
    }).catchError((e) {
      debugPrint('检查蓝牙权限失败: $e');
    });
  }

  /// 显示引导用户开启蓝牙的对话框
  Future<void> _vmShowEnableBluetoothDialog() async {
    BuildContext context = Get.context!;
    if (!context.mounted) return;
    return LxAlert.show(
      context.s.please_turn_on_bluetooth,
      title: context.s.bluetooth_is_not_ready,
      cancelTitle: context.s.cancel,
      confirmTitle: context.s.open,
      cancelCallback: () => Get.back(),
      confirmCallback: (_) async {
        await AppSettings.openAppSettings(type: AppSettingsType.bluetooth);
        Future.delayed(const Duration(milliseconds: 1000), () {
          Get.back();
        });
      },
    );
  }

  /// 显示权限被拒绝的对话框
  Future<void> _vmShowPermissionDeniedDialog() async {
    BuildContext context = Get.context!;
    if (!context.mounted) return;
    return LxAlert.show(
      context.s.has_no_bluetooth_permission_need_to_go_settings_to_open,
      title: context.s.permission_was_denied,
      cancelTitle: context.s.cancel,
      confirmTitle: context.s.go_to_settings,
      cancelCallback: () => Get.back(),
      confirmCallback: (_) async {
        await AppSettings.openAppSettings();
        Future.delayed(const Duration(milliseconds: 1000), () {
          Get.back();
        });
      },
    );
  }
}
